package com.year.shiyi.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.year.shiyi.common.exception.BusinessException;
import com.year.shiyi.common.utils.ConfigConstant;
import com.year.shiyi.entity.mybatis.SysConfigEntity;
import com.year.shiyi.entity.mybatis.SysOssEntity;
import com.year.shiyi.mapper.SysConfigMapper;
import com.year.shiyi.service.SysConfigService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 系统配置信息表 服务实现类
 * </p>
 *
 * @author shiyi
 * @since 2021-03-04
 */
@Service
public class SysConfigServiceImpl extends ServiceImpl<SysConfigMapper, SysConfigEntity> implements SysConfigService {

    @Override
    public boolean getCaptchaStatus() {
        SysConfigEntity configEntity = this.getOne(new QueryWrapper<SysConfigEntity>()
                .eq("param_key", ConfigConstant.CAPTCHA_KEY)
        );
        String paramValue = configEntity.getParamValue();
        return (boolean) JSONObject.parseObject(paramValue).get("status");
    }

    @Override
    public <T> T getConfigObject(String key, Class<T> clazz) {
        String value = getValue(key);
        if (StringUtils.isNotBlank(value)) {
            return JSON.parseObject(value, clazz);
        }
        try {
            return clazz.newInstance();
        } catch (Exception e) {
            throw new BusinessException("获取参数失败");
        }
    }

    private String getValue(String key) {
        SysConfigEntity configEntity = this.getOne(new QueryWrapper<SysConfigEntity>()
                .eq("param_key", key)
        );
        return configEntity == null ? null : configEntity.getParamValue();
    }


}
